package com.payment.notify.datasource;

import java.lang.reflect.Method;

import com.jeeccm.modules.core.datasource.DataSource;
import com.jeeccm.modules.core.datasource.DynamicDataSourceHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


/**
 * 类名：DataSourceAspect.java<br>
 * 描述：<br>
 * 创建者：XINJF<br>
 * 创建日期：2018年3月1日 上午9:35:24<br>
 * 版本：1.0<br>
 * 修改者：<br>
 * 修改日期：<br>
 */
@Aspect  
//@Order(1)   //设置AOP执行顺序(需要在事务之前，否则事务只发生在默认库中)  
@Component 
public class DataSourceAspect {
	
	 private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceAspect.class);
	 
	 //切点  
	 @Pointcut("execution(* com.payment.notify.repository.*.*(..))")
	 public void aspect() { }  
	 
	 @Before("aspect()")
//	 @Before("@annotation(com.geeboo.core.annotation.DataSource)")
	 public void before(JoinPoint point) {
		 //获取连接点所在的目标对象
		 Object target = point.getTarget(); 
		 System.out.println("target=="+target);
		 String method = point.getSignature().getName();  
		 Class<?>[] classz = target.getClass().getInterfaces();  
		 Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
		 
		 try {
			Method m = classz[0].getMethod(method, parameterTypes);
			if (m != null && m.isAnnotationPresent(DataSource.class)) { 
				 DataSource dataSource = m.getAnnotation(DataSource.class);
				 DynamicDataSourceHolder.putDataSource(dataSource.value());
				 LOGGER.info("方法:"+m.getName()+"执行,连接数据库为:"+dataSource.value());
				 System.out.println("dataSource=="+dataSource.value());
			}
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	 }
	 
//	 @After("@annotation(com.geeboo.core.annotation.DataSource)")
//	 public void afterSwitchDS(JoinPoint point){
//		 System.out.println("清除");
//		 DynamicDataSourceHolder.clearDataSourceType();
//	 }

}
